package com.jhg.drgclinicalpathway.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.jhg.drgclinicalpathway.dao.sys.AccountDao;
import com.jhg.drgclinicalpathway.domain.sys.AccountInfo;
import org.springframework.util.StringUtils;

import java.util.Calendar;

public class JWTUtils {


    public static void main(String[] args) throws Exception {
        AccountInfo u=new AccountInfo();
        u.setId(1);
        u.set用户名("潘文榜");
        u.set密码("123");
        System.out.println(getClaimByName("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NTYzMTgzNjMsInVzZXJJZCI6MSwidXNlcm5hbWUiOiLmvZjmlofmppwifQ.S1byzA25l1fXkgZ2BaIIwB86nbGK11lPAOKxk8xEPAE", "username").asString());

    }

    /**
     * 获取签发对象
     */
    public static String getAudience(String token) throws Exception {
        String audience = null;
        try {
            audience = JWT.decode(token).getAudience().get(1);
        } catch (JWTDecodeException j) {
            //这里是token解析失败
            throw new Exception("token 解析失败");
        }
        return audience;
    }

    /**
     * 获取token
     * @param u user
     * @return token
     */
    public static String getToken(AccountInfo u) {
        Calendar instance = Calendar.getInstance();
        //默认令牌过期时间7天
        instance.add(Calendar.DATE, 7);

        JWTCreator.Builder builder = JWT.create();
        builder.withClaim("userid", u.getId())
                .withClaim("username", u.get用户名())
                .withClaim("admin",u.get管理员())
        ;

        return builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(u.get密码()));
    }

    /**
     * 验证token合法性 成功返回token
     */
    public static DecodedJWT verify(String token,String secret) throws Exception{
        if(StringUtils.isEmpty(token)){
            throw new Exception("token不能为空");
        }
        JWTVerifier build = JWT.require(Algorithm.HMAC256(secret)).build();
        return build.verify(token);
    }

    /**
     * 通过载荷名字获取载荷的值
     */
    public static Claim getClaimByName(String token, String name){


        return JWT.decode(token).getClaim(name);
    }
}
